package com.neusoft.databus.agent.parser;

import java.util.List;
import java.util.Map;

import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.MapContext;

import com.neusoft.databus.common.bean.CommandBean;
import com.neusoft.databus.common.bean.MetricBean;
import com.neusoft.databus.common.parser.Parser;
import com.neusoft.databus.common.utils.JexlMath;
import com.neusoft.databus.common.utils.JexlUtil;

/**
 * @author sunchf
 * @date 2019年5月10日 上午10:09:44
 */
public class WangguanParser implements Parser {

    public static JexlEngine jexlEngine = new JexlBuilder().create();

    @Override
    public Object parseCollectRequest(final CommandBean commandBean) {
        return null;
    }

    @Override
    public void parseCollectResponse(final CommandBean commandBean) {
        commandBean.getResourceBean().stream().forEach(it -> {
            final List<MetricBean> metrics = it.getMetrics();
            final JexlContext jexlContext = new MapContext();
            jexlContext.set("Math", JexlMath.getInstance());
            metrics.stream().filter(m -> m.isExecutedSuccess()).forEach(data -> {
                jexlContext.set(data.getVariable(), data.getOriginalValue());
            });

            metrics.stream().filter(m -> m.isExecutedSuccess()).forEach(metric -> {
                final Map<String, Object> config = metric.getRule();
                final String script = (String) config.get("script");
                if (null != script) {
                    metric.setValue(WangguanParser.jexlEngine.createScript(script).execute(jexlContext));
                }
                final String expression = (String) config.get("ex");
                if (null != expression) {
                    metric.setValue(JexlUtil.evaluate(expression, jexlContext));
                }
            });

        });
    }

}
